package com.holy.sh.couviewholy.holy_text;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.TextView;


/**
 * Holy Email :victorhhl@163.com
 * Create by Holy on 2019/8/13
 * Description :
 */
public class ShimmerTextView extends android.support.v7.widget.AppCompatTextView {

    private int mDx;
    private LinearGradient linearGradient;
    private Paint mPaint;
    private Bitmap mBitmap;
    public ShimmerTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint=getPaint();
        int length= (int) mPaint.measureText(getText().toString());
        creatAnim(length);
        creatLineargradient(length);
    }

    private void creatLineargradient(int length) {
        linearGradient=new LinearGradient(-length,0,0,0,new int[]{getCurrentTextColor(),0xff00ff00,
                getCurrentHintTextColor()},new float[]{0f,0.5f,1f},Shader.TileMode.CLAMP);

    }

    private void creatAnim(int length) {

        ValueAnimator animator=ValueAnimator.ofInt(0,2*length);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mDx = (int) animation.getAnimatedValue();
                postInvalidate();
            }
        });

        animator.setRepeatMode(ValueAnimator.RESTART);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setDuration(2000);
        animator.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Matrix matrix = new Matrix();
        matrix.setTranslate(mDx,0);
        linearGradient.setLocalMatrix(matrix);
      /*  1. boolean getLoaclMatrix(Matrix localM); 如果shader有一个非本地的矩阵将返回true.
    localM：如果不为null将被设置为shader的本地矩阵.
        2. void setLocalMatrix(Matrix localM);
    设置shader的本地矩阵,如果localM为空将重置shader的本地矩阵。 */

        mPaint.setShader(linearGradient);
        super.onDraw(canvas);
    }
}
